const webSocket = require("ws") //引入ws服务器模块
const url = require("url")
const ws = new webSocket.Server({ port: 8000 }) //创建服务器,端口为8000
let clients = {}
let clientNum = 0
ws.on("connection", (client, req) => {
  //连接客户端
  //给客户端编号,也就是参与聊天的用户
  let name = replaceAll(`${req.url}`, "/", "")
  if (name !== "look") {
    client.name = name
  } else {
    client.name = clientNum + 1
  }

  if (clients[client.name] && name !== "look") {
    let parms = {
      code: -1,
      msg: "用户已存在",
    }
    console.log(clients)
    client.send(JSON.stringify(parms))
  } else {
    clients[client.name] = client
    let num = Object.keys(clients).length

    let parms = {
      code: 1,
      name: `${client.name}`,
      msg: "上线",
      num: `${num}`,
      names: Object.keys(clients),
    }
    console.log("==>parms", parms)
    broadcast(client, JSON.stringify(parms))
  }
  // 用户的聊天信息
  client.on("message", (msg) => {
    console.log("用户" + client.name + "操作")
    //广播数据发送输出
    broadcast(client, msg)
  })
  //报错信息
  client.on("error", (err) => {
    if (err) {
      console.log(err)
    }
  })
  // 下线
  client.on("close", () => {
    delete clients[client.name]
    let parms = {
      code: -2,
      msg: "游戏异常结束",
      name: `${client.name}`,
    }
    broadcast(client, JSON.stringify(parms))
    console.log("用户" + client.name + "下线了~~")
  })
})

//广播方法
function broadcast(client, msg) {
  for (var key in clients) {
    clients[key].send("" + msg)
  }
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") // $& means the whole matched string
}
function replaceAll(str, match, replacement) {
  return str.replace(new RegExp(escapeRegExp(match), "g"), () => replacement)
}
